<template>
  <div class="adaptive-image-container" :style="containerStyle">
    <img
      :src="src"
      :alt="alt"
      class="adaptive-image"
      :class="{ loaded: isLoaded }"
      :style="imageStyle"
      @load="handleLoad"
      @error="handleError"
    />
    <!-- 加载状态 -->
    <div v-if="showLoading" class="loading-placeholder">
      <slot name="loading">Loading...</slot>
    </div>
    <!-- 错误状态 -->
    <div v-if="showError" class="error-placeholder">
      <slot name="error">Failed to load image</slot>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, CSSProperties } from 'vue'

interface Props {
  src: string
  alt?: string
  width?: string | number
  height?: string | number
  maxWidth?: string | number
  maxHeight?: string | number
  bgColor?: string
}

const props = withDefaults(defineProps<Props>(), {
  alt: '',
  width: '100%',
  height: 'auto',
  maxWidth: 'none',
  maxHeight: 'none',
  bgColor: 'transparent',
})

const isLoaded = ref(false)
const hasError = ref(false)

const containerStyle = computed<CSSProperties>(() => ({
  width: typeof props.width === 'number' ? `${props.width}rpx` : props.width,
  height: typeof props.height === 'number' ? `${props.height}rpx` : props.height,
  maxWidth: typeof props.maxWidth === 'number' ? `${props.maxWidth}rpx` : props.maxWidth,
  maxHeight: typeof props.maxHeight === 'number' ? `${props.maxHeight}rpx` : props.maxHeight,
  backgroundColor: props.bgColor,
}))

const imageStyle = computed<CSSProperties>(() => ({
  opacity: isLoaded.value ? 1 : 0,
  transition: 'opacity 0.3s ease',
}))

const showLoading = computed(() => !isLoaded.value && !hasError.value)
const showError = computed(() => hasError.value)

const handleLoad = () => {
  isLoaded.value = true
  hasError.value = false
}

const handleError = () => {
  hasError.value = true
  isLoaded.value = false
}
</script>

<style scoped>
.adaptive-image-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: inherit;
  border-radius: 4px;
}

.adaptive-image {
  flex-shrink: 0;
  width: 100%;
  min-width: 0;
  min-height: 0;
  object-fit: contain;
  object-position: center;
  transition: opacity 0.3s ease;
}

.loaded {
  /* 新增加载完成状态 */
  opacity: 1;
}

.loading-placeholder,
.error-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  display: flex; /* 补充缺失属性 */
  align-items: center;
  justify-content: center;
  width: 100%;
  font-size: 14px;
  color: #666; /* 修正：nolo → color */
  background-color: rgba(245, 245, 245, 0.8);
}
</style>
